package com.zhhs.galaxyott.activity.movieDetailActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.ipanel.chongqing.playlibrary.core.ActivityJumpManager;
import com.zhhs.galaxyott.Constant;
import com.zhhs.galaxyott.MyApplication;
import com.zhhs.galaxyott.R;
import com.zhhs.galaxyott.activity.DeviceCenterActivity;
import com.zhhs.galaxyott.activity.VPInterface.IPresenter;
import com.zhhs.galaxyott.adapters.MovieDetailAdapter;
import com.zhhs.galaxyott.beans.MovieDetailRecBean;
import com.zhhs.galaxyott.beans.PlayUrlBean;
import com.zhhs.galaxyott.http.api.RequestMaker;
import com.zhhs.galaxyott.httpVolley.base.ResponseListener;
import com.zhhs.galaxyott.httpVolley.response.MovieDetailRecommendResponse;
import com.zhhs.galaxyott.httpVolley.response.MovieDetailResponse;
import com.zhhs.galaxyott.httpVolley.response.UniversalResponse;
import com.zhhs.galaxyott.sharepreference.SharedPrefHelper;
import com.zhhs.galaxyott.utils.DateUtils;
import com.zhhs.galaxyott.utils.Logs;
import com.zhhs.galaxyott.utils.OrderTipDialog;
import com.zhhs.galaxyott.utils.OrderTipDialog.DialogCallback;
import com.zhhs.galaxyott.utils.OrderTipforLackofMoneyDialog;
import com.zhhs.galaxyott.utils.OrderTipforLackofMoneyDialog.DialogCallback2;
import com.zhhs.galaxyott.utils.PromptsUtils;
import com.zhhs.galaxyott.utils.PurchaseOrPayUtils;

public class MovieDetailPresenter implements IPresenter<MovieDetailHolder> {

    private Activity mContext;
    MovieDetailHolder mViewHolder;

    private SharedPrefHelper sp;
    List<MovieDetailRecBean> listData = new ArrayList<MovieDetailRecBean>();

    MovieDetailAdapter adapter;

    private double price;
    private String movieName;
    private String HttpUrl;
    private String progId;
    public static Boolean isOrder = false;
    private String OrderMsg;
    protected OrderTipDialog dialog;
    protected OrderTipforLackofMoneyDialog dialogforlackMoeny;

    public MovieDetailPresenter(Activity context) {
        this.mContext = context;
        sp = SharedPrefHelper.getInstance(context);

        isOrder = false;
    }

    @Override
    public void attachView(MovieDetailHolder view) {
        this.mViewHolder = view;
    }

    public void loadData() {
        //如果是第三方应用跳转
        if(((MovieDetailActivity) mContext).movieid == 0 && ((MovieDetailActivity) mContext).vodId != null){


        }else {
            getMovieDetail();
        }
        getRecommandList();
    }
    // private void getIsOrder() {
    // RequestMaker.getIsOrder(sp.getsmartcard(), Constant.paymovieId, new
    // ResponseListener<IsOrderResponse>() {
    //
    // @Override
    // public void onResponse(IsOrderResponse result) {
    // Logs.logD("DEBUG_DT", "THIS IS getIsOrder-->result:" + result.getResult()
    // + "errCode" + result.errCode
    // + "movieId" + Constant.paymovieId);
    // if (result.getResult() == 1) {
    // isOrder = true;
    // mViewHolder.operate_purchase.setText("播放");
    // mViewHolder.operate_vip.setVisibility(View.GONE);
    // } else {
    // isOrder = false;
    // }
    //
    // }
    //
    // @Override
    // public void onError(VolleyError error) {
    // Logs.logD("DEBUG_DT", "THIS IS getIsOrder-->ERR");
    // }
    // });
    //
    // }

    private void getMovieDetail() {
        int pid = ((MovieDetailActivity) mContext).movieid;
        String smartcardid = sp.getsmartcard();

        RequestMaker.getMovieDetail(mContext, pid, smartcardid, new ResponseListener<MovieDetailResponse>() {

            @Override
            public void onResponse(MovieDetailResponse result) {

                if (result.Beans == null) {
                    return;
                }

                Logs.logD("DEBUG_DT", "THIS IS getMovieDetail-->" + result.errCode + result.msg);
                if (result.errCode == 0) {
                    mViewHolder.poster_name.setSelected(true);
                    mViewHolder.ename.setSelected(true);
                    movieName = result.Beans.getName();
                    mViewHolder.poster_name.setText(result.Beans.getName());
                    mViewHolder.ename.setText(result.Beans.getEname());
                    mViewHolder.watch_number.setText("共" + result.Beans.getWatchNum() + "人看过");
                    mViewHolder.type.setText("类型:");
                    mViewHolder.director_actor.setText("导演：" + result.Beans.getDirector() + "   " + "主演："
                            + result.Beans.getActor());
                    mViewHolder.introdution.setText(result.Beans.getIntro());

                    progId = result.Beans.getMediaid() + "-sfyx";
                    price = result.Beans.getPrice();
                    if (price == 0) {
                        mViewHolder.operate_purchase.setText("免费");
                    } else {
                        mViewHolder.operate_purchase.setText("单片" + price + "元");
                    }

                    Logs.logD("DEBUG_DT", "THIS IS getMovieDetail-->getIsAuthed:" + result.Beans.getIsAuthed());
                    if (result.Beans.getIsAuthed() == 1) {
                        isOrder = true;
                    } else {
                        isOrder = false;
                    }

                    // 判断是否购买
                    if (((MovieDetailActivity) mContext).sp.getIsVip() || result.Beans.getIsAuthed() == 1) {
                        mViewHolder.operate_purchase.setText("播放");
                        mViewHolder.operate_vip.setVisibility(View.GONE);
                    }
                    Glide.with(mContext).load(result.Beans.getImgurl()).placeholder(R.drawable.movie_detail_post_def)
                            .crossFade().into(mViewHolder.poster);
                    if (result.Beans.getIsFavorite() >= 1) {
                        mViewHolder.operate_collect.setText("取消收藏");
                    } else {
                        mViewHolder.operate_collect.setText("收藏");
                    }

                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS getMovieDetail-->ERR");
            }
        });
    }

    private void getRecommandList() {
        int pageNo = 1;
        int pageRow = 100;

        RequestMaker.getMovieDetailRecommend(mContext, pageNo, pageRow,
                new ResponseListener<MovieDetailRecommendResponse>() {

                    @Override
                    public void onResponse(MovieDetailRecommendResponse result) {

                        if (result.Beans == null || result.Beans.size() == 0) {
                            return;
                        }

                        Logs.logD("DEBUG_DT", "THIS IS getMovieDetailRecommend:" + "size" + result.Beans.size());

                        if (result.errCode == 0) {

                            listData = result.Beans;

                            adapter = new MovieDetailAdapter(mContext, listData);
                            mViewHolder.setGridView(adapter);
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS getMovieDetailRecommend-->ERR");
                    }
                });

    }

    public void addWatchRecord() {
        String watchtime = DateUtils.dateToStringFormat_YH(new java.util.Date());
        RequestMaker.addWatchRecord(mContext, Constant.paymovieId, sp.getsmartcard(), watchtime,
                new ResponseListener<UniversalResponse>() {

                    @Override
                    public void onResponse(UniversalResponse result) {
                        Logs.logD("DEBUG_DT", "THIS IS addCollected-->result:" + result);
                        if (result.errCode == 0) {

                        }

                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS addCollected-->ERR");
                    }
                });
    }

    public void operateCollect() {

        int pid = ((MovieDetailActivity) mContext).movieid;
        String smartcardid = sp.getsmartcard();
        RequestMaker.addCollected(mContext, pid, smartcardid, new ResponseListener<UniversalResponse>() {

            @Override
            public void onResponse(UniversalResponse result) {
                Logs.logD("DEBUG_DT", "THIS IS addCollected-->" + result.errCode);
                if (result.errCode == 0) {
                    if (result.getResult() == 0)
                        mViewHolder.operate_collect.setText("取消收藏");
                    else {
                        // PromptsUtils.showToast(mContext, "收藏失败");
                    }
                } else {
                    // PromptsUtils.showToast(mContext, "收藏失败");
                }
            }
            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS addCollected-->ERR");

            }
        });
    }
    public void CancelCollect() {
        int pid = ((MovieDetailActivity) mContext).movieid;
        String smartcardid = sp.getsmartcard();
        RequestMaker.delCollected(mContext, pid, smartcardid, new ResponseListener<UniversalResponse>() {
            @Override
            public void onResponse(UniversalResponse result) {
                Logs.logD("DEBUG_DT", "THIS IS delCollected-->" + result.errCode);
                if (result.errCode == 0) {
                    if (result.getResult() == 0)
                        mViewHolder.operate_collect.setText("收藏");
                    else {
                        // PromptsUtils.showToast(mContext, "取消收藏失败");
                    }
                } else {
                    // PromptsUtils.showToast(mContext, "取消收藏失败");
                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "THIS IS delCollected-->ERR");

            }
        });

    }

    // typeId 栏目ID(如不知道栏目ID可传-1)
    // vodId 影片的ID(可传内部与外部ID)
    // playType 播放类型：1为电影,非1为剧集
    // baseFlag 0：包月，2：按次点播
    // idType 可选参数
    // 影片ID类型(如是外部ID需要把值设成FSN)
    public void getUrl() {

        if (!Constant.isProducted) {
            // 免费(美国队长)
            // progId = "SFYX201601061837" + "-sfyx";
            // 付费
            progId = "SFYX201603181216" + "-sfyx";
            // progId = "SFYX201601061842" + "-sfyx";
            // 1元
            // progId = "SFYX201606061446" + "-sfyx";
        }
        Logs.logD("DEBUUG_LC", "THIS IS progId-->" + progId);
        String typeId = "-1";
        String playType = "1";
        String idType = "FSN";
        String baseFlag = "2";

        String epg_url = sp.getepgUrl();
        // 外部Id 按次
        HttpUrl = epg_url + "/defaultHD/en/Auth_removeBase_nor.jsp?typeId=" + typeId + "&progId=" + progId
                + "&playType=" + playType + "&idType=" + idType + "&baseFlag=" + baseFlag
                + "&contentType=0&business=1&appBackUrl=";

        if (sp.getIsVip()) {
            // 外部Id 包月
            HttpUrl = epg_url + "/defaultHD/en/go_authorization.jsp?typeId=" + typeId + "&progId=" + progId
                    + "&playType=" + playType + "&idType=" + idType + "&baseFlag=" + "0"
                    + "&contentType=0&business=1&appBackUrl=";
        }

        // HttpUrl = epg_url + "/defaultHD/en/go_authorization.jsp"
        // + "?typeId=-1&playType=1&progId=4490391&contentType=0&business=1";
        // 茁壮提供测试内部Id
        // HttpUrl = epg_url +
        // "/defaultHD/en/go_authorization.jsp?typeId=-1&playType=1&progId=" +
        // 4278497
        // + "&contentType=0&business=1&baseFlag=0";
        // HttpUrl = epg_url + "/defaultHD/en/Auth_removeBase_nor.jsp?typeId=" +
        // typeId + "&progId=" + 4490391
        // + "&playType=" + playType + "&baseFlag=" + baseFlag +
        // "&contentType=0&business=1&appBackUrl=";

        Logs.logD("DEBUG_LC", "THIS IS -->HttpUrl:" + HttpUrl);

        VolleyForGet(HttpUrl);

    }

    public synchronized void VolleyForGet(final String HttpUrl) {
        final PlayUrlBean result = new PlayUrlBean();

        StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    Logs.logD("DEBUG_LC", "THIS IS -->onResponse:" + response);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject != null) {
                        result.setPlayFlag(jsonObject.optString("playFlag"));
                        result.setMessage(jsonObject.optString("message"));
                        result.setPlayUrl(jsonObject.optString("playUrl"));
                        result.setConfirmUrl(jsonObject.optString("confirmUrl"));

                        Logs.logD(
                                "DEBUG_LC",
                                "THIS IS -->onResponse:getPlayFlag" + result.getPlayFlag() + "url:"
                                        + result.getPlayUrl() + "confirmUrl:" + result.getConfirmUrl() + "message:"
                                        + result.getMessage());

                        if (result.getConfirmUrl() != null && result.getConfirmUrl().length() > 0) {
                            // 价格大于0的情况下,没有订购与订购过期的情况
                            if (price > 0) {
                                if (!isOrder) {
                                    // OrderMsg = "本次购买价格为" + price +
                                    // "元，有效期为48小时，" + "请您点击确认购买";
                                    OrderMsg = "您将购买《" + movieName + "》价格为" + price + "元，可在48小时内使用当前机顶盒反复观看，请问您确认购买吗？";
                                } else {// 添加过期提示,改变订购状态
                                    Constant.contentId = Constant.paymovieId;
                                    Logs.logD("DEBUG_LC", "THIS IS Constant.contentId:" + Constant.contentId);
                                    PurchaseOrPayUtils.addOrderToBackstage(sp, 1, price, 2);
                                    OrderMsg = "影片内容已失效,请您重新订购！" + "本次购买价格为" + price + "元，有效期为48小时。";
                                }

                                dialog = new OrderTipDialog(mContext, OrderMsg, new DialogCallback() {
                                    public void Confirm() {
                                        dialog.dismiss();
                                        VolleyForGet(result.getConfirmUrl());

                                    }

                                    public void Cancel() {
                                        mViewHolder.operate_purchase.setText("单片" + price + "元");
                                    }

                                });
                                dialog.show();
                            } else {
                                VolleyForGet(result.getConfirmUrl());
                            }

                        } else if (result.getPlayFlag().equals("1") && result.getPlayUrl().length() > 1) {
                            String playurl = result.getPlayUrl().substring(result.getPlayUrl().indexOf("rtsp"),
                                    result.getPlayUrl().length());
                            playMovie(playurl, movieName);
                            // 付费影片订购信息反馈给后台
                            if (price > 0 && !isOrder) {
                                // Constant.contentId = Constant.paymovieId;
                                // PurchaseOrPayUtils.addOrderToBackstage(sp, 1,
                                // price, 1);
                                // Toast.makeText(mContext, "订购成功,影片将在48小时后失效！",
                                // 1).show();
                                PromptsUtils.showCustomToast(mContext, "订购成功");
                            }
                            if (price > 0) {
                                Constant.contentId = Constant.paymovieId;
                                PurchaseOrPayUtils.addOrderToBackstage(sp, 1, price, 1);
                                isOrder = true;
                            }

                            Logs.logD("DEBUG_LC", "THIS IS -->playurl:" + playurl);

                        } else if (result.getMessage().equals("106")) {

                            OrderMsg = "您可用于本业务的金额不足，请您充值订购后观看";

                            // 添加余额不足订购提示

                            dialogforlackMoeny = new OrderTipforLackofMoneyDialog(mContext, OrderMsg,
                                    new DialogCallback2() {

                                        @Override
                                        public void pay_confirm(Double priceNum) {
                                            if (priceNum == 0.0) {
                                                PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, price * 100);
                                            } else {
                                                PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, priceNum * 100);
                                            }
                                        }

                                        @Override
                                        public void fast_fill50() {
                                            PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, 50.0 * 100);

                                        }

                                        @Override
                                        public void fast_fill100() {
                                            PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, 100.0 * 100);

                                        }
                                    });

                            dialogforlackMoeny.show();

                        } else if (result.getMessage().equals("301")) {

                            OrderMsg = "您已欠费，请您充值订购后观看";

                            // 添加余额不足订购提示
                            dialogforlackMoeny = new OrderTipforLackofMoneyDialog(mContext, OrderMsg,
                                    new DialogCallback2() {

                                        @Override
                                        public void pay_confirm(Double priceNum) {
                                            if (priceNum == 0.0) {
                                                PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, price * 100);
                                            } else {
                                                PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, priceNum * 100);
                                            }

                                        }

                                        @Override
                                        public void fast_fill50() {
                                            PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, 50.0 * 100);

                                        }

                                        @Override
                                        public void fast_fill100() {
                                            PurchaseOrPayUtils.getPayPlatformUrlAndJump(mContext, 100.0 * 100);

                                        }
                                    });

                            dialogforlackMoeny.show();

                        } else {

                            // 添加套餐过期处理方式
                            if (sp.getIsVip()) {
                                OrderMsg = "套餐已过期,请点击确定进入套餐订购页面重新订购！";
                                sp.setIsVip(false);
                                Constant.contentId = MyApplication.getVipBean().getPackageId();
                                PurchaseOrPayUtils.addOrderToBackstage(sp, 2, price, 2);
                                OrderTipDialog dialog = new OrderTipDialog(mContext, OrderMsg, new DialogCallback() {
                                    @Override
                                    public void Confirm() {
                                        Intent intent = new Intent();
                                        intent.setClass(mContext, DeviceCenterActivity.class);
                                        intent.putExtra("number", 0);
                                        mContext.startActivity(intent);

                                    }

                                    @Override
                                    public void Cancel() {
                                        if (price == 0) {
                                            mViewHolder.operate_purchase.setText("免费");
                                        } else {
                                            mViewHolder.operate_purchase.setText("单片" + price + "元");
                                        }

                                        mViewHolder.operate_vip.setVisibility(View.VISIBLE);

                                    }
                                });
                                dialog.show();
                                return;
                            }

                            dialog = new OrderTipDialog(mContext, getMessageTip(result.getMessage()) + "，详情请咨询客服",
                                    new DialogCallback() {

                                        @Override
                                        public void Confirm() {
                                            dialog.dismiss();
                                        }

                                        @Override
                                        public void Cancel() {

                                        }
                                    }, true);
                            dialog.show();

                            // PromptsUtils.showToast(mContext,
                            // getMessageTip(result.getMessage()));
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    PromptsUtils.showToast(mContext, "业务暂时无法办理");
                    Logs.logD("DEBUG_LC", "THIS IS -->getUrl:JSONException");
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                Logs.logD("DEBUG_LC", "THIS IS -->getUrl:err");
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", sp.getCookies());
                return headers;

            }

        };
        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        mQueue.add(stringRequest);

    }

    public void playMovie(String url, String movieName) {
        String playType = "RTSP";
        Logs.logD("DEBUG_LC", "THIS IS -->operate_purchase");
        ActivityJumpManager.startToPlay(mContext, movieName, url, playType);
        addWatchRecord();
    }

    // payChannel String 商户编码：ccn+16位字符串，如：ccnf82d132f9bb018ca
    // userName String 用户名 (选填)
    // orderId String 商户订单号
    // payAmount String 支付金额，单位（分）
    // targetId String 支付终端编号（机顶盒编号）
    // cardNo String 支付终端卡号（智能卡号）
    // public void payJump(String playUrl) {
    // ComponentName component = new ComponentName("com.crunii.ccn.tvhall",
    // "com.crunii.ccn.tvhall.activity.PayActivity");
    // Intent intent = new Intent();
    // intent.setComponent(component);
    //
    // intent.putExtra("payurl", playUrl);
    //
    // String orderId = "SFYX" + new Date().getTime() + ((int) ((Math.random() *
    // 9 + 1) * 100000));
    // String payAmount = "1";
    // String targetId = sp.getStbid();
    // String cardNo = sp.getsmartcard();
    //
    // // intent.putExtra("payurl",
    // // "http://192.168.5.74:9000/ccn-pay/payPlatform" + "?payChannel="
    // // + "ccn1ec48caab3179e60" + "&userName= " + "&orderId=" + orderId +
    // // "&payAmount=" + payAmount
    // // + "&targetId=" + targetId + "&cardNo=" + cardNo + "&extend=充值缴费"
    // // + "&notifyUrl= http://192.168.5.73/ccn-tv/cz/notify" +
    // // "&homeUrl=myccntvhall://platformapi/home"
    // // + "&returnUrl=myccntvhall://platformapi/return" +
    // // "&rechargeType=1&rechargeAccount=0");
    //
    // mContext.startActivity(intent);
    // // mContext.finish();
    // }

    // public void getPayPlatformUrlAndJump() {
    //
    // String orderId = "SFYX" + new Date().getTime() + ((int) ((Math.random() *
    // 9 + 1) * 100000));
    // String payAmount = "1";
    // String targetId = sp.getStbid();
    // String cardNo = sp.getsmartcard();
    //
    // String returnUrl = "myccntvhall://platformapi/return";
    // String homeUrl = "myccntvhall://platformapi/home";
    //
    // RequestMaker.getPayPlatformURL(targetId, cardNo, payAmount, returnUrl,
    // homeUrl,
    // new ResponseListener<getPayPlatformURLResponse>() {
    //
    // @Override
    // public void onResponse(getPayPlatformURLResponse result) {
    // Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->" + result.errCode +
    // result.getPayurl());
    // if (result != null && result.errCode == 0) {
    //
    // String playUrl = result.getPayurl();
    //
    // payJump(playUrl);
    // } else {
    // Toast.makeText(mContext, "请求失败，请重试", 1).show();
    // }
    // }
    //
    // @Override
    // public void onError(VolleyError error) {
    // Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->ERR");
    // Toast.makeText(mContext, "请求错误", 1).show();
    // }
    // });
    //
    // }

    private String getMessageTip(String message) {
        if (message.equals("107")) {
            OrderMsg = "扣费处理失败,请稍后再试";
        } else if (message.equals("103")) {
            OrderMsg = "产品不存在或产品未激活";
        } else if (message.equals("104")) {
            OrderMsg = "产品已订购";
        } else if (message.equals("105")) {
            OrderMsg = "影片价格未定义";
        } else if (message.equals("109")) {
            OrderMsg = "内容不存在";
        } else if (message.equals("202")) {
            OrderMsg = "该用户不支持在线订购";
        } else if (message.equals("203")) {
            OrderMsg = "产品将下线,不支持订购";
        } else if (message.equals("206")) {
            OrderMsg = "业务类型不存在";
        } else if (message.equals("207")) {
            OrderMsg = "内容类型不存在";
        } else if (message.equals("208")) {
            OrderMsg = "订购/退订处理失败";
        } else {
            OrderMsg = "数据异常,异常码为：" + message;
        }
        return OrderMsg;
    }

    @Override
    public void detachView() {
        this.mViewHolder = null;
    }

}
